<template>
  <div class="memberAside">
    <!-- 侧边栏顶部 -->
    <div class="memberAside-top">
      <a href="javascript:;" class="edit-avatar" title="点击修改头像">
        <img src="../../assets/images/avatar.png" alt="" class="touxiang">
      </a>
      <h2>{{ memberPhone }}</h2>
      <div class="mobantu-check">
        <a href="javascript:;" class="usercheck checkin" :class="{ changeCheck: isActive }"
           @click="checkIn">{{ checkin }}</a>
        <p>每日签到送积分</p>
      </div>
    </div>

    <!-- 侧边栏菜单 -->
    <div class="memberAside-bottom">
      <ul v-for="option in options" :key="option.url">
        <li class="usermenu-charge" @click="toContent(option.url)">
          <a href="javascript:;">{{ option.name }}</a>
        </li>
      </ul>
    </div>

    <!-- AI聊天窗口 -->
    <div class="chat-modal" v-if="showChat">
      <div class="chat-header">
        <h3>健身助手</h3>
        <span class="close-btn" @click="showChat = false">×</span>
      </div>
      <div class="chat-body">
        <div v-for="(msg, index) in messages" :key="index"
             :class="['message', msg.role]">
          <div class="message-bubble">
            {{ msg.content }}
          </div>
        </div>
        <div v-if="isLoading" class="loading">AI正在思考中...</div>
      </div>
      <div class="chat-input">
        <input v-model="inputMessage"
               @keyup.enter="sendMessage"
               placeholder="输入你的健身问题..."/>
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { addCheckIn, getMemberIntegral, updateMemberIntegral, aiChat, getAIDialogList } from "@/api/allApi";
import dayjs from 'dayjs';

export default {
  name: "MemberAside",
  data() {
    return {
      options: [
        { name: '全部课程', url: 'allCourse' },
        { name: '在线充值', url: 'onlinePay' },
        { name: '充值记录', url: 'rechargeRecord' },
        { name: '升级VIP', url: 'vipCard' },
        { name: '购买记录', url: 'buyRecord' },
        { name: '我的资料', url: 'myProfile' },
        { name: '修改密码', url: 'changePassword' },
        { name: 'AI健身助手', url: 'ai-chat' }
      ],
      // 签到相关
      isActive: false,
      checkin: '今日签到',
      checkTime: '',
      today: '',
      // 用户信息
      memberPhone: '',
      member: {},
      // 聊天相关
      showChat: false,
      messages: [],
      inputMessage: '',
      isLoading: false
    };
  },
  created() {
    this.member = JSON.parse(window.localStorage.getItem('access-member')) || {};
    this.checkTime = window.localStorage.getItem('access-checkTime');
  },
  mounted() {
    this.initDate();
    this.checkSignInStatus();
  },
  methods: {
    // 初始化日期
    initDate() {
      const date = new Date();
      this.today = dayjs(date).format('YYYY-MM-DD');
      this.memberPhone = this.member.memberPhone || '';
    },

    // 检查签到状态
    checkSignInStatus() {
      if (this.today === this.checkTime) {
        this.checkin = '今日已签';
        this.isActive = true;
      }
    },

    // 菜单跳转
    toContent(url) {
      if (url === 'ai-chat') {
        this.showChat = true;
        this.fetchHistory();
        return;
      }
      this.$router.push({ path: url });
    },

    // 获取聊天历史
    async fetchHistory() {
      try {
        this.isLoading = true;
        const res = await getAIDialogList({
          memberNo: this.member.memberNo
        });
        if (res?.status === 200 && Array.isArray(res.data)) {
          console.log('历史记录:', res.data);
          this.messages = res.data.map(item => ({
            role: item.type === 0 ? 'user' : 'assistant',
            content: item.content,
            timestamp: dayjs(item.createTime).valueOf(),
            meta: {
              dialogNo: item.dialogNo,
              createTime: item.createTime
            }
          })).sort((a, b) => a.timestamp - b.timestamp);

          if (this.messages.length === 0) {
            this.messages.push(this.createSystemMessage('暂无聊天记录'));
          }

          this.$nextTick(() => this.scrollToBottom());
        }
      } catch (error) {
        console.error('获取历史记录失败:', error);
        this.messages.push(this.createSystemMessage('加载失败: ' + error.message));
      } finally {
        this.isLoading = false;
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim()) return;

      const userMsg = {
        role: 'user',
        content: this.inputMessage,
        timestamp: Date.now()
      };
      this.messages.push(userMsg);
      this.inputMessage = '';

      try {
        this.isLoading = true;
        const res = await aiChat({
          memberNo: this.member.memberNo,
          message: userMsg.content
        });

        this.messages.push({
          role: 'assistant',
          content: res.data,
          timestamp: Date.now()
        });

        await this.fetchHistory();
      } catch (error) {
        console.error('发送失败:', error);
        this.messages.push({
          role: 'system',
          content: '服务暂时不可用，请稍后再试',
          timestamp: Date.now()
        });
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    // 系统消息创建
    createSystemMessage(content) {
      return {
        role: 'system',
        content,
        timestamp: Date.now(),
        meta: { isSystem: true }
      };
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.chat-body');
        if (container) {
          container.scrollTo({
            top: container.scrollHeight,
            behavior: 'smooth'
          });
        }
      });
    },

    // 签到功能
    checkIn() {
      if (this.today !== this.checkTime) {
        window.localStorage.setItem('access-checkTime', this.today);
        this.isActive = true;
        this.checkin = '今日已签';
        addCheckIn({
          memberNo: this.member.memberNo
        }).then(res => {
          alert(res.data.message);
          updateMemberIntegral({
            memberNo: this.member.memberNo,
            price: -1
          });
          this.getMemberIntegral();
        }).catch(err => {
          alert(err.data.message);
        });
      }
    },

    // 获取会员积分
    getMemberIntegral() {
      getMemberIntegral({
        memberNo: this.member.memberNo
      }).then(res => {
        this.MemberIntegral = res.data;
      }).catch(err => {
        console.log(err.message);
      });
    }
  }
}
</script>

<style scoped>
/* 全局重置 */
li, ul, a, h2, p {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  font-weight: normal;
}

/* 侧边栏主容器 */
.memberAside {
  --primary-color: #00c996;
  --secondary-color: #ff5f33;
  --text-dark: #333;
  --text-light: #888;
  --bg-light: #fbfbfb;
  --border-color: #eaeaea;

  position: relative;
  float: left;
  width: 200px;
  height: 100vh;
  background: var(--bg-light);
  padding: 20px;
  box-sizing: border-box;
}

/* 顶部区域 */
.memberAside-top {
  width: 160px;
  margin: 0 auto 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color);
  text-align: center;
}

.edit-avatar {
  display: inline-block;
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
}

.touxiang {
  width: 100%;
  height: 100%;
  border: 1px solid var(--primary-color);
  border-radius: 50%;
  object-fit: cover;
}

.memberAside-top h2 {
  font-size: 14px;
  color: var(--text-dark);
  margin: 8px 0;
}

/* 签到区域 */
.mobantu-check {
  padding-top: 15px;
}

.usercheck {
  display: inline-block;
  width: 76px;
  padding: 3px 12px;
  background: var(--secondary-color);
  color: white !important;
  border-radius: 15px;
  font-size: 12px;
  transition: background 0.3s;
}

.usercheck.changeCheck {
  background: #aaa;
}

.mobantu-check p {
  font-size: 12px;
  color: var(--text-light);
  margin-top: 3px;
}

/* 菜单区域 */
.memberAside-bottom {
  margin-top: 20px;
}

.usermenu-charge {
  width: 160px;
  height: 50px;
  margin: 0 auto 5px;
  line-height: 50px;
  text-align: center;
  transition: background 0.2s;
  border-radius: 4px;
}

.usermenu-charge:hover {
  background: rgba(0, 201, 150, 0.1);
}

.usermenu-charge a {
  display: block;
  font-size: 16px;
  color: var(--text-light);
  transition: color 0.2s;
}

.usermenu-charge:hover a {
  color: var(--primary-color);
}

/* 聊天窗口样式 */
.chat-modal {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 360px;
  height: 520px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 1000;
  transform: translateY(5%);
  opacity: 0;
  animation: modalEnter 0.3s ease-out forwards;
}

@keyframes modalEnter {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.chat-header {
  padding: 16px 20px;
  background: var(--primary-color);
  color: white;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  font-size: 16px;
  font-weight: 500;
}

.close-btn {
  cursor: pointer;
  font-size: 24px;
  transition: opacity 0.2s;
  line-height: 1;
}

.close-btn:hover {
  opacity: 0.8;
}

.chat-body {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f8fafb;
}

.message {
  margin: 12px 0;
  display: flex;
  animation: messageFade 0.3s ease-out;
}

/* AI消息居左 */
.message.assistant {
  justify-content: flex-start;
}

/* 用户消息居右 */
.message.user {
  justify-content: flex-end;
}

@keyframes messageFade {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-bubble {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 16px;
  line-height: 1.4;
  font-size: 14px;
  word-break: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* AI消息样式 */
.message.assistant .message-bubble {
  background: white;
  color: var(--text-dark);
  border: 1px solid #eee;
  border-radius: 16px 16px 16px 4px;
}

/* 用户消息样式 */
.message.user .message-bubble {
  background: var(--primary-color);
  color: white;
  border-radius: 16px 16px 4px 16px;
}

.chat-input {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #eee;
  background: white;
}

.chat-input input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.chat-input input:focus {
  border-color: var(--primary-color);
  outline: none;
}

.chat-input button {
  padding: 8px 24px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background 0.3s;
}

.chat-input button:hover {
  background: #00b386;
}

.loading {
  color: var(--text-light);
  text-align: center;
  padding: 12px;
  font-size: 13px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chat-modal {
    right: 10px;
    bottom: 10px;
    width: calc(100vw - 220px);
    height: 70vh;
  }
}
</style>